import { sqlMain } from '@utils/dbconf'
import { usermap } from '@maps/index'
import { success,error,SQL_ERROR } from '@utils/response'
import { analysis } from '@utils/request'
import { encode, decode } from 'js-base64'
import { toToken,tokenTo,changeToken } from '@utils/tokenOper'
import redisDB from '@utils/redisconf'
import fs from 'fs'
const { Random } = require('mockjs')


const AVATAR_PATH = 'files/avatar/'

export const avatar = async (req,res) =>{
  try{
    const { data,file,token } = res.locals
    if(!token) return res.send(error(500,'未知的用户'))
    const { id,acc,pass } = await tokenTo(token)//acc、pass、type
    const { name,type,size } = data
    const types = {'image/jpeg':'jpg','image/png':'png'}
    //*删除源文件
    const newpath = `${AVATAR_PATH}${id}-${Random.string('lower',8)}.${types[type]}`
    
    await redisDB.set('2',id,{ path:newpath,filetype:type })
    fs.rename(file.path,newpath,err=> res.send(err? error(500,'上传失败'):success({})) )
  }catch(e){
    console.log(e)
    return res.send(SQL_ERROR)}
} 